<template>
	<!--  质检方案-->
	<div class="content">
		<div class="pageSearchView">
			<el-form :inline="true" :model="searchParam" class="demo-form-inline">
				<el-form-item label="质检方案编码">
					<el-input v-model="searchParam.code" placeholder="请输入质检方案编码" clearable style="width: 200px" />
				</el-form-item>
				<el-form-item label="质检方案名称">
					<el-input v-model="searchParam.name" placeholder="请输入质检方案名称" clearable style="width: 200px" />
				</el-form-item>
				<el-form-item label="质检类型">
					<el-select v-model="searchParam.qualityType" placeholder="请选择质检类型" clearable style="width: 200px">
						<el-option v-for="(item, index) of qualityTypeList" :key="index" :label="item.label"
											 :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" :icon="Search" @click="handleSearch()">查询</el-button>
					<el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div style="display: flex;">
			<div class="pageTableView" style="width: 400px;border-radius: 10px 0 0 10px;">
				<div class="pageTableMenuViewStock" style="position: sticky;top: 0">
					<div class="pageTableTitle">
						<div>产品信息</div>
					</div>
					<div class="pageTableButViewStock">
						<el-button :icon="Plus" @click="handleAddProduct()">新建产品</el-button>
					</div>
				</div>
				<div style="display: flex;justify-content: space-between ;">
					<el-form-item label="产品名称 ">
						<el-select v-model="schemeTreeForm.productId" filterable clearable style="width: 200px">
							<el-option v-for="item in productData" :key="item.id" :value="item.id"
												 :label="item.productCode" />
						</el-select>

					</el-form-item>
					<el-button type="primary" @click="searchSchemeTree">搜索</el-button>
				</div>

				<div style="overflow-y: auto;height: calc(100vh - 310px)">
					<el-tree :data="schemeTree" node-key="id" :default-expand-all="false" accordion
									 :props="{ children: 'children' }" :disable-branch-nodes="true">
						<template #default="{ node, data }">
							<div class="custom-tree-node">
								<div v-if="node.level === 1"
										 :title="data.productCode"
										 style="width: 240px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer;font-weight: 700">
									{{ data.productCode }}
								</div>
								<div v-if="node.level == 2" :class="data.id == procedureRowInfo.id ? 'is-penultimate' : ''"
										 @click="productCodeSearch(data)"
										 :title="data.procedureName"
										 style="width: 240px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer;color:#777">
									{{ data.procedureName }}
								</div>
								<span>
<!--									新建工序-->
								<el-button type="text" @click="addProduct(data)" :icon="Plus" v-if="node.level == 1"></el-button>
									<!--									编辑工序-->
								<el-button type="text" @click="editProduct(data,node.level)"
													 :icon="Edit"></el-button>
									<!--									删除工序-->
								<el-button link @click="remove(data)" type="danger"
													 :icon="Delete"></el-button>
            	</span>
							</div>
						</template>

					</el-tree>
				</div>
			</div>
			<div class="pageTableView" style="border-radius: 0 10px 10px 0">
				<div class="pageTableMenuView">
					<div class="pageTableTitle">列表信息</div>
					<div class="pageTableButView">
						<el-button :icon="Plus" @click="handleAdd()" :disabled="!procedureRowInfo.id">新建</el-button>
					</div>
				</div>
				<!-- 表格 -->
				<el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 320px)">
					<el-table-column label="序号" align="center" width="70">
						<template #default="scope">
							<!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{ (pageSearch.current - 1) * pageSearch.pageSize
						+ scope.$index + 1 }}
						</template>
					</el-table-column>
					<el-table-column prop="code" label="质检方案编码" align="center" min-width="200" />
					<el-table-column prop="name" label="质检方案名称" align="center" min-width="200" show-overflow-tooltip />
					<el-table-column prop="qualityType" label="质检类型" align="center" min-width="150">
						<template #default="scope">
							<span> {{ getQualityTypeByValue(scope.row.qualityType) }} </span></template>
					</el-table-column>
					<el-table-column prop="qualityIsLive" label="是否启用" align="center" min-width="100">
						<template #default="scope">
							<div v-if="scope.row.qualityIsLive == 0">-</div>
							<div v-else>是</div>
						</template>
					</el-table-column>

					<el-table-column label="操作" align="center" fixed="right" width="280">
						<template #default="scope">
							<el-button @click="handleConfigEdit(scope.row)" type='warning' text size="small"
												 :icon="DocumentCopy">配置质检项
							</el-button>
							<el-button @click="handleEdit(scope.row)" type="text" size="small" plain
												 :icon="Edit">编辑
							</el-button>
							<el-button @click="handleDel(scope.row)" text type="danger" size="small"
												 :icon="Delete">删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
				<div class="pagePagination">
					<el-pagination background v-model:current-page="pageSearch.current"
												 v-model:page-size="pageSearch.pageSize" :page-sizes="[10, 20, 50, 100, 200, 500]"
												 layout="total, sizes, prev, pager, next" :total="pageTotal" @size-change="handleSizeChange"
												 @current-change="handleCurrentChange" />
				</div>
			</div>

		</div>
		<!-- 弹窗表单 -->
		<el-dialog v-model="showCrud" :title="crudTitle">
			<el-form :model="formData" label-width="90px" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
				<el-row :gutter="10">
					<el-col :span="12">
						<el-form-item required label="方案编码" prop="code">
							<el-input v-model="formData.code" placeholder="请输入方案名称" style="width: 300px" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item required label="方案名称" prop="name">
							<el-input v-model="formData.name" placeholder="请输入方案名称" style="width: 300px" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item required label="质检方式" prop="qualityWay">
							<el-select v-model="formData.qualityWay" placeholder="请选择质检方式" clearable filterable
												 style="width: 300px">
								<el-option v-for="(item, index) of qualityWayList" :key="index" :label="item.label"
													 :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="formData.qualityWay == 2">
						<el-form-item required label="比例抽检">
							<el-input-number v-model="formData.proportionNumber" :min="0" :max="1" />
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="formData.qualityWay == 3">
						<el-form-item required label="固定抽检">
							<el-input-number v-model="formData.qualityNumber" :step="1" step-strictly :min="0" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item required label="质检类型" prop="qualityType">
							<el-select v-model="formData.qualityType" filterable placeholder="请选择质检类型" clearable
												 style="width: 300px">
								<el-option v-for="(item, index) of qualityTypeList" :key="index" :label="item.label"
													 :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="formData.qualityType == 4">
						<el-form-item required label="巡检间隔" prop="qualityInterval">
							<el-input-number v-model="formData.qualityInterval" :step="0.0001" :min="0" />
							（小时）
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="是否启用" prop="qualityIsLive">
							<el-select v-model="formData.qualityIsLive" placeholder="请选择是否启用" style="width: 300px">
								<el-option :key="1" label="是" :value="true" />
								<el-option :key="0" label="否" :value="false" />
							</el-select>
						</el-form-item>
					</el-col>
					<!--					<el-col :span="24">-->
					<!--						<el-form-item label="方案说明" prop="qualityRemark">-->
					<!--							<el-input v-model="formData.qualityRemark" style="width: 770px" :rows="2" type="textarea"-->
					<!--												placeholder="请输入方案说明" />-->
					<!--						</el-form-item>-->
					<!--					</el-001col>-->
				</el-row>
			</el-form>
			<template v-slot:footer>
				<div class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
				</div>
			</template>
		</el-dialog>
		<el-dialog v-model="configTableShow" title="配置质检项" width="95%" top="5vh">
			<el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
				<div style="width: 100%;display: flex;justify-content: flex-end;margin: 10px 0;gap:20px">
					<el-button type="danger" :loading="downLoading" :disabled="multipleSelection.length == 0"
										 v-if="activeName == 'first'" @click="delQualityLine">删除质检项
					</el-button>
					<el-button type="primary" :loading="downLoading" @click="handleExport">导出质检项</el-button>
					<el-upload v-model:file-list="fileList" list-type="xlsx"
										 :show-file-list="false"
										 :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove"
										 :on-exceed="handleExceed" :before-upload="beforeUpload" :http-request="customUpload">
						<el-button type="primary">导入质检模版</el-button>
					</el-upload>
					<el-button type="primary">
						<!--						http://121.228.40.79:9012/download/MESPDA.apk-->
						<a :href="apiPost+'/download/质检项导入模板.xlsx'"> 下载质检模版 </a>
					</el-button>
				</div>
				<el-tab-pane label="质检列表" name="first">
					<el-table :data="configTable" height="300px" border @selection-change="handleSelectionChange"
										style="width: 100%">
						<el-table-column type="selection" width="55" align="center" />
						<el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
						<el-table-column prop="testitemName" align="center" label="质检项名称" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="testitemType" align="center" label="质检项分类" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="dataType" align="center" label="数值类型" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="judgmentCriteria" align="center" label="检验标准录入方式" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="otherDefect" align="center" label="标准值" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="upperValue" align="center" label="上公差" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="lowerValue" align="center" label="下公差" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="lowerBias" align="center" label="下警戒值" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="upperBias" align="center" label="上警戒值" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="excelCoordinate" align="center" label="SPC坐标" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="defaultValue" align="center" label="检验默认值" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="spcInspection" align="center" label="SPC检" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="fullSizeInspection" align="center" label="全尺寸检" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="fullSizeCoordinate" align="center" label="全尺寸坐标" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="toolCoordinate" align="center" label="量具坐标" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="failNameCode" align="center" label="文件名称代码" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="defectMethod" align="center" label="不良判定方式" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="badReasons" align="center" label="不良原因" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="memo" align="center" label="备注" min-width="180" show-overflow-tooltip />
						<el-table-column prop="createUser" align="center" label="创建人" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="createTime" align="center" label="创建时间" min-width="180"
														 show-overflow-tooltip />
						<el-table-column align="center" width="200" fixed="right">
							<template #header>
								<el-button :icon="Plus" size="small" @click="handleAddConfigLine">新建</el-button>
							</template>
							<template #default="scope">
								<el-button @click="handleEditConfigLine(scope.row, scope.$index)" size="small" plain
													 :icon="Edit"> 编辑
								</el-button>
								<el-button type="danger" plain size="small" :icon="Delete"
													 @click="handleConfigDelete(scope.row, scope.$index)"> 删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="可适用物料" name="second">
					<el-table :data="materialTable" height="300px" border style="width: 100%">
						<el-table-column label="序号" type="index" align="center" width="80" />
						<el-table-column prop="materialName" align="center" label="物料名称" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="materialNo" align="center" label="物料编码" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="materialProperties" align="center" label="物料属性" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="basicUnit" align="center" label="基本单位" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="conversionUnit" align="center" label="单位换算率" min-width="180"
														 show-overflow-tooltip />
						<el-table-column prop="weightNumConvert" align="center" label="重量个数转换比" min-width="180"
														 show-overflow-tooltip />
						<el-table-column align="center" width="150" fixed="right">
							<template #header>
								<el-button :icon="Plus" size="small" @click="handleAddMaterialLine">新建</el-button>
							</template>
							<template #default="scope">
								<el-button type="danger" plain size="small" :icon="Delete"
													 @click="handleMaterialDelete(scope.row, scope.$index)"> 删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
			</el-tabs>
			<template v-slot:footer>
				<div class="dialog-footer">
					<el-button @click="configTableShow = false">关闭</el-button>
				</div>
			</template>
			<!-- 配置质检项 -->
			<el-dialog v-model="showConfig" title="配置质检项" width="1000" top="5vh">
				<el-form :model="configData" :rules="outInRules" label-width="130px" class="demo-ruleForm" ref="formRef">
					<el-row :gutter="10">
						<!-- 检验标准录入方式 -->
						<el-col :span="12">
							<el-form-item label="质检项名称" prop="testitemName" required>
								<el-input v-model="configData.testitemName" placeholder="请输入质检项名称"
													style="width: 300px" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="质检项分类" prop="testitemType" required>
								<el-select v-model="configData.testitemType" clearable placeholder="质检项分类"
													 style="width: 300px">
									<el-option v-for="item in testitemTypeList" :key="item" :label="item"
														 :value="item" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="数值类型" prop="dataType" required>
								<el-select v-model="configData.dataType" clearable placeholder="数值类型"
													 style="width: 300px">
									<el-option v-for="item in dataTypeList" :key="item" :label="item" :value="item" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="检验标准录入方式" prop="judgmentCriteria">
								<el-select v-model="configData.judgmentCriteria" clearable placeholder="检验标准录入方式"
													 style="width: 300px">
									<el-option v-for="item in judgmentCriteriaList" :key="item" :label="item"
														 :value="item" />
								</el-select>
							</el-form-item>
						</el-col>
						<!-- 标准值 -->
						<el-col :span="12">
							<el-form-item label="标准值" prop="otherDefect">
								<el-input v-model="configData.otherDefect" placeholder="请输入标准值" style="width: 300px" />
							</el-form-item>
						</el-col>
						<!-- 上公差 -->
						<el-col :span="12">
							<el-form-item label="上公差" prop="upperValue">
								<el-input v-model="configData.upperValue" placeholder="请输入上公差" style="width: 300px" />
							</el-form-item>
						</el-col>
						<!-- 下公差 -->
						<el-col :span="12">
							<el-form-item label="下公差" prop="lowerValue">
								<el-input v-model="configData.lowerValue" placeholder="请输入下公差" style="width: 300px" />
							</el-form-item>
						</el-col>
						<!-- 下警戒值 -->
						<el-col :span="12">
							<el-form-item label="下警戒值" prop="lowerBias">
								<el-input v-model="configData.lowerBias" placeholder="请输入下警戒值" style="width: 300px" />
							</el-form-item>
						</el-col>
						<!-- 上警戒值 -->
						<el-col :span="12">
							<el-form-item label="上警戒值" prop="upperBias">
								<el-input v-model="configData.upperBias" placeholder="请输入上警戒值" style="width: 300px" />
							</el-form-item>
						</el-col>
						<!-- SPC坐标 -->
						<el-col :span="12">
							<el-form-item label="SPC坐标" prop="excelCoordinate">
								<el-input v-model="configData.excelCoordinate" placeholder="请输入SPC坐标"
													style="width: 300px" />
							</el-form-item>
						</el-col>
						<!-- 默认值 -->
						<el-col :span="12">
							<el-form-item label="检验默认值" prop="defaultValue">
								<el-input v-model="configData.defaultValue" placeholder="请输入默认值" style="width: 300px" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="SPC检" prop="spcInspection">
								<el-select v-model="configData.spcInspection" clearable placeholder="SPC检"
													 style="width: 300px">
									<el-option v-for="item in yesOrNo" :key="item" :label="item" :value="item" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="全尺寸检" prop="fullSizeInspection">
								<el-select v-model="configData.fullSizeInspection" clearable placeholder="全尺寸检"
													 style="width: 300px">
									<el-option v-for="item in yesOrNo" :key="item" :label="item" :value="item" />
								</el-select>
							</el-form-item>
						</el-col>
						<!-- 全尺寸坐标 -->
						<el-col :span="12">
							<el-form-item label="全尺寸坐标" prop="fullSizeCoordinate">
								<el-input v-model="configData.fullSizeCoordinate" placeholder="请输入全尺寸坐标"
													style="width: 300px" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="量具坐标" prop="toolCoordinate">
								<el-input v-model="configData.toolCoordinate" placeholder="请输入量具坐标"
													style="width: 300px" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="文件名称代码" prop="excelCoordinate">
								<el-input v-model="configData.failNameCode" placeholder="请输入文件名称代码"
													style="width: 300px" />
							</el-form-item>
						</el-col>
						<!-- 不良判定方式 -->
						<el-col :span="12">
							<el-form-item label="不良判定方式" prop="defectMethod" required>
								<el-select v-model="configData.defectMethod" clearable placeholder="不良判定方式"
													 style="width: 300px">
									<el-option v-for="item in defectMethodList" :key="item" :label="item"
														 :value="item" />
								</el-select>
							</el-form-item>
						</el-col>
						<!-- 不良判定方式 -->
						<el-col :span="12">
							<el-form-item label="不良原因" prop="schemeTaskRemark">
								<el-select v-model="configData.schemeTaskRemark" multiple filterable
													 :disabled="configData.defectMethod != '枚举选择'" clearable placeholder="不良原因"
													 style="width: 300px">
									<el-option v-for="item in badReasonsList" :key="item.id" :label="item.description"
														 :value="item.description" />
								</el-select>
							</el-form-item>
						</el-col>
						<!-- 备注 -->
						<el-col :span="12">
							<el-form-item label="备注" prop="memo">
								<el-input v-model="configData.memo" placeholder="请输入备注" style="width: 300px" />
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<template v-slot:footer>
					<div class="dialog-footer">
						<el-button @click="showConfig = false">取消</el-button>
						<el-button type="primary" @click="handleSaveConfig">保存</el-button>
					</div>
				</template>
			</el-dialog>
			<el-dialog v-model="showMaterial" title="添加可适用物料" width="500">
				<el-form :model="materialData" label-width="130px" class="demo-ruleForm">
					<el-row :gutter="10">
						<el-form-item label="选择物料">
							<el-select v-model="materialId" placeholder="请选择选择物料" filterable clearable style="width: 300px">
								<el-option v-for="(item, index) of materialList" :key="index" :label="item.materialName"
													 :value="item.id">
									<span style="float: left">{{ item.materialName }}</span>
									<span style="
          float: right;
          color: var(--el-text-color-secondary);
          font-size: 13px;
        "> {{ item.materialNo }} </span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-row>
				</el-form>
				<template v-slot:footer>
					<div class="dialog-footer">
						<el-button @click="showMaterial = false">取消</el-button>
						<el-button type="primary" @click="handleSaveMaterial">保存</el-button>
					</div>
				</template>
			</el-dialog>
		</el-dialog>


		<el-dialog v-model="addProductShow" :title="wareEdit?'编辑产品':'新建产品'" width="600px" top="5vh">
			<el-form label-width="80px">
				<el-row :gutter="10">
					<el-form-item label="选择产品">
						<el-select v-model="wareForm.productId" placeholder="请选择选择产品" filterable clearable style="width: 380px">
							<el-option v-for="(item, index) of productList" :key="index" :label="item.productName"
												 :value="item.id">
								<span style="float: left">{{ item.productName }}</span>
								<span style="float: right;color:#777">编码：{{ item.productCode }}</span>
							</el-option>
						</el-select>
					</el-form-item>
				</el-row>
			</el-form>
			<template v-slot:footer>
				<div class="dialog-footer">
					<el-button @click="addProductShow = false">取消</el-button>
					<el-button type="primary" @click="handleSaveProduct">保存</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog v-model="addWareShow" :title="wareEdit ? '编辑工序' : '新建工序'" width="600px" top="5vh">
			<el-form label-width="130px">
				<el-row :gutter="10">
					<el-form-item label="输入工序名称">
						<el-input v-model="wareForm.procedureName" placeholder="请输入工序名称" style="width: 380px" />
					</el-form-item>
				</el-row>
			</el-form>
			<template v-slot:footer>
				<div class="dialog-footer">
					<el-button @click="addWareShow = false">取消</el-button>
					<el-button type="primary" @click="handleAddProductChildren">保存</el-button>
				</div>
			</template>
		</el-dialog>

	</div>
</template>
<script lang="ts" setup>
import axiosInstance from '@/utils/http/api';
import { Delete, DocumentCopy, Edit, Plus, Refresh, Search } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import { computed, reactive, ref } from 'vue';
import axios from 'axios';

onMounted(() => {
	handleSearch();
	getMaterial();
	getOption();
});
const productData = ref([]);
const getOption = () => {
	axiosInstance.post('/api/basedataProduct/getAll', {})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			productData.value = res.data;
		});
};
// 文件上传
const fileList = ref([]);
const customUpload = async ({ file, data }) => {
	const formDataResult = new FormData();
	formDataResult.append('file', file); // 确保 file 是 Blob 类型
	try {
		axiosInstance.post('/api/fileUpload/upload-template', formDataResult).then(async res => {
			if (res.code == 200) {
				// fileList.value = [];
				console.log(configTable.value);

				console.log(res.data);
				// configTable.value = res.data
				handleSaveConfig(res.data);
				// ElMessage.success('导入质检模版成功!');
			} else {
				fileList.value = [];
			}
		});
	} catch (error) {
		console.error('上传失败:', error);
	}
};

const beforeUpload = (file) => {

};
const handleRemove = (file, uploadFiles) => {
	console.log(file, uploadFiles);
};

const handlePreview = (uploadFile) => {
	console.log(uploadFile);
};

const handleExceed = (files, uploadFiles) => {
	ElMessage.warning(
		`The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
		} totally`
	);
};

const beforeRemove = (uploadFile, uploadFiles) => {
	return ElMessageBox.confirm(
		`Cancel the transfer of ${uploadFile.name} ?`
	).then(
		() => true,
		() => false
	);
};

const pageSearch = ref({
	current: 1,
	pageSize: 10
});

const badReasonsList = ref([]);

const defectMethodList = ref([
	'无',
	'手工输入',
	'枚举选择'
]);

const judgmentCriteriaList = ref([
	'无',
	'手工输入',
	'按标准检验'
]);

const yesOrNo = ref([
	'是',
	'否'
]);

const configTableShow = ref(false);

const activeName = ref('first');

const handleClick = (e) => {
	activeName.value = e.props.name;
};
// 配置质检项表
const configTable = ref([]);

const delQualityLine = () => {
	ElMessageBox.confirm('确认删除选中数据吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		configTable.value = configTable.value.filter(configItem =>
			!multipleSelection.value.some(selectedItem =>
				selectedItem.testitemName === configItem.testitemName &&
				selectedItem.testitemType === configItem.testitemType
			)
		);
    const jsonParam = JSON.parse(rowInfo.value.qualityJson);
    jsonParam.configTable = configTable.value
    rowInfo.value.qualityJson = JSON.stringify(jsonParam);
    handleUpdateQualityScheme(rowInfo.value);
		// testitemName + testitemType作为唯一值
		//
		// 判断multipleSelection.value和configTable.value的唯一值 configTable.value匹配上的项删除
	});
};

// 可适用物料
const materialTable = ref([]);


const rowInfo = ref({});
// 点击配置质检项表
const handleConfigEdit = (e) => {
	configTable.value = [];
	const row = JSON.parse(JSON.stringify(e));
	rowInfo.value = row;

	const list = JSON.parse(row.qualityJson);
	if (list.configTable && list.configTable.length) {
		configTable.value = list.configTable;
	}
	if (list.materialTable && list.materialTable.length) {
		materialTable.value = list.materialTable;
	}
	console.log(configTable.value);

	configTableShow.value = true;
};

const apiPost = import.meta.env.VITE_API_PROXY_TARGET;

const downLoading = ref(false);
const handleExport = () => {
	downLoading.value = true;
	axios.post('/api/basedataQualityScheme/exportItemExcel', {
		id: rowInfo.value.id
	}, {
		timeout: 30000, // 与 axiosInstance 的 timeout 相同
		responseType: 'blob',
		headers: {
			BearerToken: localStorage.getItem('token') || undefined // 与请求拦截器中的设置相同
		}
	})
		.then(response => {
			console.log(response);
			const url = window.URL.createObjectURL(new Blob([response.data]));
			const link = document.createElement('a');
			link.href = url;
			const formattedDate = moment().format('YYYYMMDD');
			link.setAttribute('download', rowInfo.value.name + '质检模板' + formattedDate + '.xlsx'); // 导出的格式一定要和接口返回的文件一致
			document.body.appendChild(link);
			link.click();
			window.URL.revokeObjectURL(url);
			document.body.removeChild(link);
		})
		.finally(() => {
			downLoading.value = false;
		});

};

// 点击 质检项表新建 新建
const handleAddConfigLine = () => {
	isConfigEdit.value = false;
	configData.value = {};
	showConfig.value = true;
};

const materialList = ref({});
const schemeTree = ref([]);
const schemeTreeForm = ref({});
const getMaterial = () => {
	axiosInstance.post('/api/basedataMaterial/getAll', {})
		.then(res => {
			materialList.value = res.data;
		});

	axiosInstance.post('/api/basedataProduct/getAll', {})
		.then(res => {
			productList.value = res.data;
		});

	axiosInstance.post('/api/qualityBadCode/getAll', {})
		.then(res => {
			badReasonsList.value = res.data;
			console.log(res.data, ' res.data');
		});


	axiosInstance.post('/api/basedataQualitySchemeTree/queryAll', schemeTreeForm.value)
		.then(res => {
			schemeTree.value = res.data;
		});
};
const searchSchemeTree = () => {
	axiosInstance.post('/api/basedataQualitySchemeTree/queryAll', schemeTreeForm.value)
		.then(res => {
			schemeTree.value = res.data;
		});
};

// 点击 物料 新建
const handleAddMaterialLine = () => {
	isMaterialEdit.value = false;
	materialData.value = {};
	showMaterial.value = true;
};

// 物料删除
const handleMaterialDelete = (e, i) => {
	ElMessageBox.confirm(
		'确认删除该条物料？',
		'提示',
		{
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		}
	)
		.then(() => {
			const jsonParam = JSON.parse(rowInfo.value.qualityJson);
			jsonParam.materialTable.splice(i, 1);
			rowInfo.value.qualityJson = JSON.stringify(jsonParam);
			handleUpdateQualityScheme(rowInfo.value);
		});

};
const materialData = ref({});
const showMaterial = ref(false);
const addProductShow = ref(false);
const handleAddProduct = () => {
	wareForm.value = {};
	wareEdit.value = false;
	addProductShow.value = true;
};
const productList = ref([]);
const handleSaveProduct = () => {
	if (!wareForm.value.productId) {
		ElMessage.error('请选择产品');
		return false;
	}
	if (wareEdit.value) {
		axiosInstance.put('/api/basedataQualitySchemeTree/update', wareForm.value)
			.then(res => {
				if (res.code == 200) {
					getMaterial();
					addProductShow.value = false;
				}
			});
	} else {
		axiosInstance.post('/api/basedataQualitySchemeTree/save', wareForm.value)
			.then(res => {
				if (res.code == 200) {
					getMaterial();
					addProductShow.value = false;
				}
			});
	}

};
const addWareShow = ref(false);//编辑工序
// addProductShow//编辑产品
const wareEdit = ref(false);
const wareForm = ref({});
// 新建工序
const addProduct = (data) => {
	wareEdit.value = false;
	wareForm.value = {
		pid: data.id
	};

	addWareShow.value = true;
};

// 编辑产品 工序
const editProduct = (data, level) => {
	wareForm.value = data;
	wareEdit.value = true;
	if (level == 1) {
		addProductShow.value = true;
	} else {
		addWareShow.value = true;
	}
};

const handleAddProductChildren = () => {
	if (!wareForm.value.procedureName) {
		ElMessage.error('请输入工序名称');
		return false;
	}
	if (wareEdit.value) {
		axiosInstance.post('/api/basedataQualitySchemeTree/updateProcedureName', wareForm.value)
			.then(res => {
				if (res.code == 200) {
					getMaterial();
					addWareShow.value = false;
				}
			});
	} else {
		axiosInstance.post('/api/basedataQualitySchemeTree/save', wareForm.value)
			.then(res => {
				if (res.code == 200) {
					getMaterial();
					addWareShow.value = false;
				}
			});
	}

};

const procedureRowInfo = ref({});

const productCodeSearch = (e) => {
	procedureRowInfo.value = e;
	handleSearch();
};
// 质检列表
const isConfigEdit = ref(false);

const isConfigIndex = ref(null);

const testitemTypeList = ref([
	'功能性能检测',
	'模具入库检', '外观检验', '数量检验', '尺寸检验', 'RoHs测试', '包装检验', '标签检验', '报告检验'
]);

const dataTypeList = ref([
	'字符(外观)',
	'数字',
	'日期',
	'是/否',
	'字符(功能)'
]);

// 可适配物料
const isMaterialEdit = ref(false);

const isMaterialIndex = ref(null);
// 质检项表编辑
const handleEditConfigLine = (e, i) => {
	// e form , i index
	isConfigEdit.value = true;
	isConfigIndex.value = i;
	const param = JSON.parse(JSON.stringify(rowInfo.value));
	const jsonParam = JSON.parse(param.qualityJson);
	console.log(jsonParam);
	// jsonParam[i] = e
	configData.value = jsonParam.configTable[i];
	// schemeTaskRemark  badReasons
	configData.value.schemeTaskRemark = configData.value.badReasons?.split(',');
	showConfig.value = true;
};

const multipleSelection = ref([]);

const handleSelectionChange = (val: User[]) => {
	multipleSelection.value = val;
};

const delMultipleSelection = () => {
	ElMessageBox.confirm(
		'确认删除选中的质检项吗?',
		'提示',
		{
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'error'
		}
	)
		.then(() => {
			configTable.value = configTable.value.filter(item => {
				// 假设每个item都有一个唯一标识符，比如id
				// 这里需要根据实际情况来调整，确保正确比较两个对象是否相等
				return !multipleSelection.value.some(selected => selected.id === item.id);
			});
		});
};

const remove = (e) => {
	ElMessageBox.confirm(
		'确认删除该条信息?',
		'提示',
		{
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'error'
		}
	)
		.then(() => {
			axiosInstance.delete(`/api/basedataQualitySchemeTree/delete`, {
				data: {
					ids: [e.id]
				}
			})
				.then(res => {
					if (res.code === 200) {
						ElMessage.success('删除成功');
						getMaterial();
					}
				});
		});
};


// 通用更新接口函数
const handleUpdateQualityScheme = (updatedRowInfo) => {
		// const list = JSON.parse(updatedRowInfo.qualityJson);
		// console.log(list, 'list');
		// for (const item of list.configTable) {
		// 	if (!item.testitemName) {
		// 		ElMessage.error('请输入质检项名称');
		// 		return false;
		// 	}
		// 	if (!item.testitemType) {
		// 		ElMessage.error('请选择质检项类型');
		// 		return false;
		// 	}
		// 	if (!item.dataType) {
		// 		ElMessage.error('请选择质检项数据类型');
		// 		return false;
		// 	}
		// 	if (!item.defectMethod) {
		// 		ElMessage.error('请选择不良判定方式');
		// 		return false;
		// 	}
		// 	if (item.defectMethod == '枚举选择') {
		// 		if (!item.badReasons || item.badReasons.length == 0) {
		// 			ElMessage.error('请选择不良原因');
		// 			return false;
		// 		}
		// 	}
		// }
		// ;
		axiosInstance.put('/api/basedataQualityScheme/update', updatedRowInfo).then(res => {
			if (res.code != 200) {
				ElMessage.error(res.message);
				return false;
			}
			ElMessage.success('操作成功!');
			showConfig.value = false;
			showMaterial.value = false;
			// 刷新配置质检项列表
			handleConfigEdit(rowInfo.value);
			handleSearch();
		});
	}
;

// 质检项表删除
const handleConfigDelete = (e, i) => {
	ElMessageBox.confirm(
		'确认删除该条配置质检项？',
		'提示',
		{
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		}
	)
		.then(() => {
			const jsonParam = JSON.parse(rowInfo.value.qualityJson);
			jsonParam.configTable.splice(i, 1);
			rowInfo.value.qualityJson = JSON.stringify(jsonParam);
			handleUpdateQualityScheme(rowInfo.value);
		});

};
const materialId = ref(null);
// 报错适配物料
const handleSaveMaterial = () => {
	const jsonParam = JSON.parse(rowInfo.value.qualityJson);
	for (const item of materialTable.value) {
		if (item.id == materialId.value) {
			ElMessage.error('该物料已存在');
			return false;
		}
	}
	let param = ref({});
	for (const items of materialList.value) {
		if (items.id == materialId.value) {
			param = items;
		}
	}
	// 保存
	// 存在则push
	if (jsonParam.materialTable && jsonParam.materialTable.length) {
		jsonParam.materialTable.unshift(param);
	} else {
		// 不存在则创建
		jsonParam.materialTable = [param];

	}

	rowInfo.value.qualityJson = JSON.stringify(jsonParam);
	handleUpdateQualityScheme(rowInfo.value);
};
const formRef = ref(null);
const outInRules = reactive<FormRules<formRef>>({
	testitemName: [
		{ required: true, message: '请输入质检项名称', trigger: 'blur' }
	],
	testitemType: [
		{ required: true, message: '请选择质检项分类', trigger: 'change' }
	],
	dataType: [
		{ required: true, message: '请选择数值类型', trigger: 'change' }
	],
	defectMethod: [
		{ required: true, message: '请选择不良判定方式', trigger: 'change' }
	]
});

// 质检项表删除 新建 编辑
const handleSaveConfig = (configTable) => {
	console.log(configTable);
	console.log(Array.isArray(configTable));
	const jsonParam = JSON.parse(rowInfo.value.qualityJson);
	const isArray = Array.isArray(configTable);
// 是数组 则是导入的模板 不校验字段
	if (!isArray) {
		if (!configData.value.testitemName) {
			ElMessage.error('请输入质检项名称');
			return false;
		}
		if (!configData.value.testitemType) {
			ElMessage.error('请选择质检项分类');
			return false;
		}
		if (!configData.value.dataType) {
			ElMessage.error('请选择质检项数据类型');
			return false;
		}

		if (!configData.value.defectMethod) {
			ElMessage.error('请选择不良判定方式');
			return false;
		}

		if (configData.value.defectMethod == '枚举选择') {
			console.log(configData.value.schemeTaskRemark, 'configData.value.badReasons');
			if (!configData.value.schemeTaskRemark || configData.value.schemeTaskRemark.length == 0) {
				ElMessage.error('请选择不良原因');
				return false;
			}
		}
	}

	configData.value.createUser = localStorage.getItem('username');
	configData.value.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
	configData.value.badReasons = configData.value.schemeTaskRemark?.join(',');
	console.log(configData.value);

	if (isConfigEdit.value) {
		// configTable编辑
		jsonParam.configTable[isConfigIndex.value] = configData.value;
	} else {
		// 保存
		// 存在则push
		if (jsonParam.configTable && jsonParam.configTable.length) {

			if (Array.isArray(configTable)) {
				// 导入模版
				jsonParam.configTable = jsonParam.configTable.concat(configTable);

			} else {
				jsonParam.configTable.unshift(configData.value);

			}
		} else {
			// 不存在则创建
			if (Array.isArray(configTable)) {
				// 导入模版
				jsonParam.configTable = configTable;

			} else {
				jsonParam.configTable = [configData.value];

			}
		}
	}

	rowInfo.value.qualityJson = JSON.stringify(jsonParam);
	handleUpdateQualityScheme(rowInfo.value);
};


const pageTotal = ref(null);//页面总数
// const formData = reactive({});//form表单
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({});//页面检索条件
const showConfig = ref(false);
const configData = ref({});
const crudTitle = computed(() => {
	return isEdit.value ? '编辑' : '新建';
});//弹出层标题

// 质检方式
const qualityWayList = reactive([
	{
		label: '全检',
		value: '1'
	}, {
		label: '比例抽检',
		value: '2'
	}, {
		label: '固定抽检',
		value: '3'
	}, {
		label: '自定义抽检',
		value: '4'
	}
]);


// 判断质检类型
const getQualityTypeByValue = (e) => {
	let name = null;
	for (const item of qualityTypeList) {
		if (e == item.value) {
			name = item.label;
		}
	}
	return name;
};

// 质检类型
const qualityTypeList = reactive([
	{
		label: '首件检',
		value: '1',
		type: 'material'
	},
	{
		label: '末件检',
		value: '2',
		type: 'material'
	},
	{
		label: '生产检',
		value: '3',
		type: 'material'
	},
	{
		label: '巡检',
		value: '4',
		type: 'material'
	},
	{
		label: '入库检',
		value: '5',
		type: 'procedure'
	},
	{
		label: '出库检',
		value: '6',
		type: 'procedure'
	},
	{
		label: '来料检',
		value: '7',
		type: 'procedure'
	}
	// 继续添加更多检查类型...
]);

const ruleFormRef = ref<FormInstance>();

interface RuleForm {
	name: string;
	code: string;
	qualityWay: string;
	proportionNumber: string;
	qualityNumber: string;
	qualityType: string;
	qualityInterval: number;
	qualityIsLive: boolean;
	qualityRemark: string;
	qualityJson: string;
}


const originalFormData = reactive<RuleForm>({
	name: '',
	code: '',
	qualityWay: null,
	proportionNumber: 1,
	qualityNumber: 1,
	qualityType: '',
	qualityInterval: 1,
	qualityIsLive: true,
	qualityRemark: '',
	qualityJson: null
});

let formData = reactive<RuleForm>(originalFormData);


const rules = reactive<FormRules<formData>>({
	code: [
		{ required: true, message: '请输入方案编码', trigger: 'blur' }
	],
	name: [
		{ required: true, message: '请输入方案名称', trigger: 'blur' }
	],
	qualityWay: [
		{ required: true, message: '请选择质检方式', trigger: 'blur' }
	],
	qualityType: [
		{ required: true, message: '请选择质检类型', trigger: 'blur' }
	],
	qualityInterval: [
		{ required: true, message: '请输入巡检间隔', trigger: 'blur' }
	],
	qualityIsLive: [
		{ required: true, message: '请选择是否启用', trigger: 'blur' }
	]
});


// const paginatedData = reactive([])//列表数据
const paginatedData = ref<RuleForm[]>([]);

// 获取列表接口
const handleSearch = () => {
	axiosInstance.post('/api/basedataQualityScheme/getPage', {
		...searchParam.value,
		...pageSearch.value,
		...{
			treeId: procedureRowInfo.value.id
		}
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			const loop = JSON.parse(JSON.stringify(res.data.records));
			const dataLoop = [];
			for (const item of loop) {
				const list = JSON.parse(item.qualityJson);
				list.id = item.id;
				list.name = item.name;
				list.code = item.code;
				list.qualityJson = item.qualityJson;
				dataLoop.push(list);
			}
			paginatedData.value = dataLoop;
			pageTotal.value = res.data.total;
		});
};

const handleSizeChange = (e) => {
	pageSearch.value.pageSize = e;
	handleSearch();
};

const handleCurrentChange = (e) => {
	pageSearch.value.current = e;
	handleSearch();
};

// 重置搜索条件
const resetSearch = () => {
	searchParam.value = {};
	pageSearch.value.current = 1;
	// current.value = 1
	handleSearch();
};

// 点击新建
const handleAdd = () => {
	isEdit.value = false;
	// ruleFormRef.value.resetFields()
	formData = reactive({});
	showCrud.value = true;
};

// 编辑
const handleEdit = (row: any) => {
	isEdit.value = true;
	const param = JSON.parse(row.qualityJson);
	const list = { ...param, ...row };
	Object.assign(formData, list);
	showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
	ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		axiosInstance.delete(`/api/basedataQualityScheme/delete`, {
			data: {
				ids: [row.id]
			}
		}).then(res => {
			ElMessage.success('删除成功');
			handleSearch(); // 刷新数据
		});


	});
};


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
	if (!e) return;
	await e.validate((valid, fields) => {
		if (valid) {
			if (formData.qualityWay == 2 && !formData.proportionNumber) {
				ElMessage.error('请输入抽检比例');
				return false;
			}
			if (formData.qualityWay == 3 && !formData.qualityNumber) {
				ElMessage.error('请输入固定抽检数量');
				return false;
			}
			const jsonString = JSON.stringify(formData);
			formData.qualityJson = jsonString;
			formData.treeId = procedureRowInfo.value.id;
			if (isEdit.value) {
				// 编辑
				axiosInstance.put('/api/basedataQualityScheme/update', formData).then(res => {
					if (res.code != 200) {
						ElMessage.error(res.message);
						return false;
					}
					ElMessage.success('操作成功!');
					showCrud.value = false;
					handleSearch(); // 刷新数据
				});
			} else {
				// 新建
				axiosInstance.post('/api/basedataQualityScheme/save', formData).then(res => {
					if (res.code != 200) {
						ElMessage.error(res.message);
						return false;
					}
					ElMessage.success('操作成功!');
					showCrud.value = false;
					handleSearch(); // 刷新数据
				});
			}

		}
	});
};


// 模拟 API 调用
const addEquipment = async (data: any) => {
	// 假设这里有一个新建接口
	console.log('新建设备数据:', data);
};

const updateEquipment = async (data: any) => {
	// 假设这里有一个更新接口
	console.log('更新设备数据:', data);
};

const deleteEquipment = async (id: string) => {
	// 假设这里有一个删除接口
	console.log('删除设备ID:', id);
};
</script>
<style scoped>
.pageTableView {
	width: calc(100% - 400px)
}

.pageTableMenuViewStock {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 10px;
}

.custom-tree-node {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 14px;
	padding-right: 8px;
}

.is-penultimate {
	color: #626aef !important;
	font-weight: 700;
}
</style>
